﻿using BoriPeter.NutritionManager.FatSecret;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BoriPeter.NutritionManager.WebFormsClient
{
    public partial class FoodsSearch : BasePage
    {
        private static DataSet1 myDataSet;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                var target = Request.Form["__EVENTTARGET"];
                
                if (!String.IsNullOrEmpty(target))
                {
                    var targetsplit = target.Split('$')[2];
                    if (targetsplit == "GridView1")
                    {
                        var arg = Request.Form["__EVENTARGUMENT"];
                        var argsplit = arg.Split('$')[1];
                        int argint;
                        Int32.TryParse(argsplit, out argint);
                        int i = 0;
                        foreach (DataSet1.FoodsRow row in myDataSet.Foods.Rows)
                        {
                            if (i == argint)
                            {
                                Response.Redirect("~/AddFromFatSecret.aspx?ID=" + row.Id);
                            }
                            i++;
                        }
                    }
                }
                
            }
        }

        protected async void Button2_Click(object sender, EventArgs e)
        {
            var message = new FoodsSearchMessage(TextBox1.Text, 1);

            var result = await message.SendAsync();

            myDataSet = new DataSet1();

            if (result.Foods != null)
            {

                foreach (var food in result.Foods)
                {
                    DataSet1.FoodsRow newRow = myDataSet.Foods.NewFoodsRow();
                    newRow.Id = food.FoodId;
                    newRow.Brand = food.BrandName;
                    newRow.Name = food.FoodName;
                    myDataSet.Foods.Rows.Add(newRow);
                }
            }

            GridView1.DataSource = myDataSet.Foods;
            GridView1.DataBind();
        }

    }
}